package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.GoodsDao;
import com.atguigu.jxc.dao.GoodsTypeDao;
import com.atguigu.jxc.entity.GoodsType;
import com.atguigu.jxc.service.GoodsTypeService;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class GoodsTypeServiceImpl implements GoodsTypeService {

    @Autowired
    private GoodsTypeDao goodsTypeDao;
    @Autowired
    private GoodsDao goodsDao;

    @Override
    public String  loadGoodsType() {
        List<GoodsType> goodsTypes = goodsTypeDao.selectgoodsType();
        return this.getAllGoodsType(-1).toString(); //默认从根节点开始
    }

    private JsonArray getAllGoodsType(Integer pid) {
        JsonArray array = this.getGoodsTypeByPid(pid);
        for (int i = 0; i < array.size(); i++) {
            JsonObject obj = (JsonObject) array.get(i);
            if (obj.get("state").getAsString().equals("open")){
                continue;
            }else {
                //非根节点
                obj.add("children",this.getAllGoodsType(obj.get("id").getAsInt()));

            }
        }
        return array;
    }

    private JsonArray getGoodsTypeByPid(Integer pid) {
        JsonArray array = new JsonArray();
        List<GoodsType> goodsTypeList = goodsTypeDao.selectGoodsTypeByPid(pid);
        for (GoodsType goodsType : goodsTypeList) {
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("id",goodsType.getGoodsTypeId());
            jsonObject.addProperty("text",goodsType.getGoodsTypeName());
            jsonObject.addProperty("iconCls","goods-type");
            JsonObject object= new JsonObject();
            if (goodsType.getGoodsTypeState() == 1){
                object.addProperty("state",1);
                jsonObject.add("attributes",object);
                jsonObject.addProperty("state","closed");
            }else {
                object.addProperty("state",0);
                jsonObject.add("attributes",object);
                jsonObject.addProperty("state","open");
            }
            array.add(jsonObject);
        }
        return array;
    }


    @Override
    public void save(String goodsTypeName, Integer pId) {
        goodsTypeDao.insert(goodsTypeName,pId);
    }

    @Override
    public void delete(Integer goodsTypeId) {
        goodsDao.deleteByGoodsTypeId(goodsTypeId);
        goodsTypeDao.delete(goodsTypeId);
    }
}
